package thread.juc.cas;

/**
 * CAS compare-and-swap算法模拟
 */
public class CASArithmetic {
    public static void main(String[] args) {
        final CompareAndSwap cas = new CompareAndSwap();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                int expectedValue = cas.get();
                boolean b = cas.conpareAndSet(expectedValue, (int)(Math.random() * 101));
                System.out.println(Thread.currentThread().getName() + "  :  " + b);
            }).start();
        }
    }
}

class CompareAndSwap {
    private int value;

    public synchronized int get() {
        return value;
    }

    //比较和替换
    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        int oldValue = value;

        if (oldValue == expectedValue) {
            this.value = newValue;
        }

        return oldValue;
    }

    //V == A
    public synchronized boolean conpareAndSet(int expectedValue, int newValue) {
        return expectedValue == compareAndSwap(expectedValue, newValue);
    }
}
